package com.zzj.controller;

import com.zzj.base.Result;
import com.zzj.entity.File;
import com.zzj.service.IFileService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zzj
 * @since 2023-03-15
 */
@RestController
@RequestMapping("/file")
public class FileController {
    @Value("${system-params.file-save-path}")
    private String filePath;
    @Resource
    private IFileService fileService;

    @Transactional
    @PostMapping("uploads")
    public Result uploads(@RequestParam("files") List<MultipartFile> files) throws IOException {
        if (files.isEmpty()) {
            return Result.error("上传失败，请选择文件");
        }
        List<String> list = new ArrayList<>();
        for (int i = 0; i < files.size(); i++) {
            MultipartFile file = files.get(i);
            String url = fileService.upload(file, filePath);
            File fileData =new File();
            fileData.setUrl(url);
           fileService.save(fileData);
            list.add(url);
        }
        return Result.success("文件上传成功",list);
    }


    @Transactional
    @PostMapping("upload")
    public Result upload(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return Result.error("上传失败，请选择文件");
        }
        String url = fileService.upload(file, filePath);
        File fileData =new File();
        fileData.setType("images");
        fileData.setUrl(url);
        fileService.save(fileData);
        return Result.success("文件上传成功",url);
    }

    @Transactional
    @PostMapping("uploadVoice")
    public Result uploadVoice(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return Result.error("上传失败，请选择文件");
        }
        String url = fileService.uploadVoice(file, filePath);
        File fileData =new File();
        fileData.setUrl(url);
        fileData.setType("voices");
         fileService.save(fileData);
        return Result.success("文件上传成功",url);
    }
}
